#include "../core/core.h"
#include "unicode.h"

#ifdef __APPLE__
#include <iconv.h>
#endif

namespace	unicode
{
	int utf16toutf8(char* dest, int destsize, const wchar* src)
	{
		int size = 0;
		const wchar* tmp = src;
		while(*tmp)
		{
			if     (*tmp <= 0x007f) size += 1;
			else if(*tmp <= 0x07ff) size += 2;
			else if(*tmp <= 0xffff) size += 3;
			++ tmp;
		}
		Assert(size <= destsize);

		tmp = src;
		char* utf8_tmp = &dest[0];
		while(*tmp)
		{
			if     (*tmp <= 0x007f) {*(utf8_tmp ++) = (char)  *tmp;}
			else if(*tmp <= 0x07ff) {*(utf8_tmp ++) = (char)((*tmp&0x07C0) >>  6) | 0xc0; *(utf8_tmp ++) = (char) (*tmp&0x003f)       | 0x80;}
			else                    {*(utf8_tmp ++) = (char)((*tmp&0xf000) >> 12) | 0xe0; *(utf8_tmp ++) = (char)((*tmp&0x0fc0) >> 6) | 0x80; *(utf8_tmp ++) = (char)(*tmp&0x003f) | 0x80;}
			++ tmp;
		}
		return size;
	}

	int utf8toutf16(wchar* dest, int destsize, const char* src)
	{
		int size = 0;
		const char* utf8_tmp = src;
		while(*utf8_tmp)
		{
			if     ((*utf8_tmp & 0x80) == 0x00) utf8_tmp += 1;
			else if((*utf8_tmp & 0xe0) == 0xc0) utf8_tmp += 2;
			else if((*utf8_tmp & 0xf0) == 0xe0) utf8_tmp += 3;
			else
			{
				utf8_tmp ++;
				while((*utf8_tmp & 0xc0) == 0x80) ++ utf8_tmp;
			}
			++ size;
		}
		Assert(size <= destsize);

		utf8_tmp = src;
		wchar* unicode_tmp = &dest[0];
		while(*utf8_tmp)
		{
			if     ((*utf8_tmp & 0x80) == 0x00) {*unicode_tmp = (wchar) *(utf8_tmp ++);}
			else if((*utf8_tmp & 0xe0) == 0xc0) {*unicode_tmp = (wchar)(*(utf8_tmp ++)&0x1f) <<  6; *unicode_tmp |= (wchar) *(utf8_tmp ++)&0x3f;}
			else if((*utf8_tmp & 0xf0) == 0xe0) {*unicode_tmp = (wchar)(*(utf8_tmp ++)&0x0f) << 12; *unicode_tmp |= (wchar)(*(utf8_tmp ++)&0x3f) << 6; *unicode_tmp |= (wchar)*(utf8_tmp ++)&0x3f;}
			else
			{
				*unicode_tmp = '?';
				utf8_tmp ++;
				while((*utf8_tmp & 0xc0) == 0x80) ++ utf8_tmp;
			}
			++ unicode_tmp;
		}
		return size;
	}
}